import { View } from '@tarojs/components';
import { useState } from "react";
import Taro, {chooseImage} from '@tarojs/taro';
import { ChatMessage } from "@/types/conservationType";
import { Textarea, Button, Uploader, Image} from "@taroify/core";
import {GuideOutlined, PhotoOutlined, Stop} from "@taroify/icons";
import {uploadFile} from "@/api/upload";

export default function Index(props: { onSend: (message: ChatMessage) => void, generating: boolean, onStop: () => void }) {
  const { onSend, generating, onStop} = props;
  const [message, setMessage] = useState('');
  const [files, setFiles] = useState<Uploader.File[]>([])

// 组件中的上传处理函数
  const handleUpload = async () => {
    try {
      const { tempFiles } = await chooseImage({
        count: 9, // 最大选择数量
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
      });

      // 并行上传所有文件
      const uploadPromises = tempFiles.map(async (file) => {
        try {
          const res = await uploadFile(file.path);
          return {
            type: file.type,
            url: process.env.TARO_APP_BASE_URL + res.url, // 根据实际接口返回字段调整
            name: `file_${Date.now()}` // 生成唯一文件名
          };
        } catch (error) {
          Taro.showToast({
            title: `${file.path} 上传失败`,
            icon: 'none'
          });
          return null;
        }
      });


      // 等待所有上传完成
      const results = await Promise.all(uploadPromises);
      // 过滤掉上传失败的文件
      const successfulUploads = results.filter(item => item !== null) as Uploader.File[];

      // 更新文件列表
      setFiles(prev => [...prev, ...successfulUploads]);

    } catch (error) {
      console.error('选择文件失败:', error);
      await Taro.showToast({
        title: '选择文件失败',
        icon: 'none'
      });
    }
  };
  const handleStopGenerate = async () => {
    onStop()
  }

  // 处理文本发送
  const handleSend = async () => {
    if(generating) {
      await Taro.showToast({icon: 'none', title: '正在生成回复，请勿发送消息'});
      return
    }
    if (message.trim() || files.length !== 0) {
      const newMessage: ChatMessage = {
        role: 'user',
        contents: []
      }
      if (message.trim())
        newMessage.contents.push({
          type: 'text',
          content: message,
        })

      if (files.length !== 0)
        files.forEach((file) => {
          if(file.url)
            newMessage.contents.push({
              type: 'image',
              content: file.url,
            })
        })

      onSend(newMessage);
      setMessage('');
      setFiles([])
    }
  };


  return (
    <View
      style={{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
        backgroundColor: '#F3F4F6',
        borderRadius: '30rpx',
        padding: '25rpx',
      }}
    >
      <View style={{width:'100%', marginBottom: '10rpx'}}>
        {files.length > 0 && (
          <View style={{display: 'flex'}}>
            {files.map((image, index) => (
              <View key={index} style={{position: 'relative', padding: '4rpx', width: '152rpx'}}>
                <Image
                  src={image.url}
                  mode='aspectFill'
                  style={{
                    width: '144rpx',
                    height: '144rpx',
                    borderRadius: '16rpx',
                    border: '2rpx solid #eee'
                  }}
                />
                <Button
                  shape='round'
                  size='mini'
                  style={{
                    position: 'absolute',
                    top: '-12rpx',
                    right: '-12rpx',
                    width: '44rpx',
                    height: '44rpx',
                    minWidth: 'auto',
                    lineHeight: '44rpx',
                    backgroundColor: '#ff4d4f',
                    color: '#fff',
                    zIndex: 2
                  }}
                  onClick={() => setFiles(files.filter((item) => item !== image))}
                >
                  ×
                </Button>
              </View>
            ))}
          </View>
        )}
      </View>

      <View style={{width:'100%', flexGrow: 1, maxHeight: '400rpx', overflow: 'hidden', display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
        {/* 输入框 */}
        <Textarea
          style={{
            overflowY: 'auto',
            height: '100%',
            fontSize: '32rpx',
          }}
          maxlength={-1}
          autoHeight
          value={message}
          onChange={(e) => setMessage(e.detail.value)}
          placeholder='请输入消息'
          confirmType='send'
        />

        {/* 操作按钮容器 */}
        <View
          style={{
            display: "flex",
            paddingLeft: '15rpx',
            justifyContent: 'flex-end',
          }}
        >
          {!generating && <Button
            icon={<PhotoOutlined style={{fontSize: '48rpx', color: '#666'}} />}
            onClick={handleUpload}
            shape='round'
            style={{
              width: '75rpx',
              height: '75rpx',
              padding: 0,
              backgroundColor: '#f0f2f5',
              transition: 'transform 0.2s'
            }}
          />}
          {(message !== "" || files.length !== 0) && !generating && (
            <Button
              icon={<GuideOutlined style={{ fontSize: '48rpx', color: '#fff' }} />}
              onClick={handleSend}
              shape='round'
              style={{
                marginLeft: '5rpx',
                width: '75rpx',
                height: '75rpx',
                padding: 0,
                background: 'linear-gradient(135deg, #6a11cb 20%, #2575fc 80%)',
                transform: 'scale(1.05)'
              }}
            />
          )}
          {generating && <Button
            icon={<Stop style={{fontSize: '60rpx', color: '#2CD8D5'}} />}
            onClick={handleStopGenerate}
            shape='round'
            style={{
              width: '75rpx',
              height: '75rpx',
              padding: 0,
              borderColor: '#C5C1FF',
              backgroundColor: '#f0f2f5',
              transition: 'transform 0.2s'
            }}
          />}
        </View>
      </View>
    </View>
  );
};
